
const Promise = require('bluebird');
const moment = require('moment');
const newsService = require('../../service/news/news');
const statisticsService = require('../../service/news/statistics');
const cacheService = require('../../service/cache');
const _ = require('lodash');

let News = {};

/**
 *获取头条
 */
News.getAll = (req, res, next)=> {

    if (!req.query.date || !moment(req.query.date, 'YYYY-MM-DD').isValid()) {
        return res.error('传入日期有误', 400)
    }
    let date = moment(req.query.date, 'YYYY-MM-DD').endOf('d');
    let where = {
        status: 5,   //处于发表状态
        imgKey: {$ne: null},
        publishedAt: {$lte: date}
    };
    let datas, code = {};

    //  拉取排行数据信息
    newsService.getTopInfo({
        where: where,
        fields: 'publishedAt'
    }, {options: {sort: {publishedAt: -1}}})
        .then((data)=> {
            if (!data) {
                return Promise.resolve([])
            }
            let realTime = data.publishedAt;
            let start = moment(realTime).startOf('d');
            let end = moment(realTime).endOf('d');

            where.publishedAt = {$gte: start, $lte: end};
            //  拉取排行的数据
            return newsService.getManyTopInfos({
                where, fields: '-__v -createdAt -updatedAt'
            }, {options: {
                sort: {publishedAt: -1},
                lean: true
            }})
        })
        .then((result)=> {
            datas = result;
            let i, j;
            let arr = [];
            for (i = 0; i < datas.length; i++) {
                let data = datas[i];
                for (j = 0; j < data.stocks.length; j ++) {
                    arr.push({code: data.stocks[j], type: 'stock'})
                }
                for (j = 0; j < data.themes.length; j ++) {
                    arr.push({code: data.themes[j], type: 'theme'})
                }
            }
            //  取对应的theme和stock的值， 并在内存里面进行存储
            return Promise.each(arr, (par)=> {
                return cacheService.extract(par.code, par.type)
                    .then((data)=> {
                        code[par.code] = data
                    })
            })
        })
        .then(()=> {
            let i;
            for (i = 0; i < datas.length; i++) {
                datas[i].stocks = _.compact(_.map(datas[i].stocks, (par)=> {
                    return {
                        name: code[par].name,
                        eCode: code[par].eCode,
                        iCode: code[par].iCode
                    }
                }));
                datas[i].themes = _.compact(_.map(datas[i].themes, (par)=> {
                    return {
                        name: code[par].name,
                        eCode: code[par].eCode,
                        iCode: code[par].iCode
                    }
                }));
            }
            //  根据涨跌进行一个排序
            return Promise.each(datas, newsService.sortStockByZhangDie)
        })
        .then(()=> {
            res.success(datas)
        })
        .catch((err)=> {
            next(err)
        })
};
//
// /**
//  *  统计头条数据
//  */
// News.statistic = (req, res, next)=> {
//
//     if (!req.query.nid) {
//         return res.error('请传入头条Id', 400)
//     }
//
//     let viewPercent = req.query.viewPercent;    //百分比
//     let keepTime = req.query.keepTime;  //秒
//     let nid = req.query.nid;
//
//     statisticsService.recordNews({viewPercent, keepTime, nid})
//         .then(()=> {
//             res.success()
//         })
//         .catch((err)=> {
//             next(err)
//         })
// };

module.exports = News;